package cn.edu.cug.cs.gtl.plugins.catalog.tree;

import cn.edu.cug.cs.gtl.apis.ui.AbstractApplication;
import cn.edu.cug.cs.gtl.apis.ui.actions.AbstractAction;
import cn.edu.cug.cs.gtl.apis.ui.catalogtree.CatalogTree;
import cn.edu.cug.cs.gtl.apis.ui.tree.TreeNodeData;
import cn.edu.cug.cs.gtl.protos.DataGroup;
import cn.edu.cug.cs.gtl.protos.DataItem;
import cn.edu.cug.cs.gtl.protos.DataKey;
import cn.edu.cug.cs.gtl.protos.FileKey;
import cn.edu.cug.cs.gtl.utils.impl.DataItemManagerImpl;
import cn.edu.cug.cs.gtl.utils.postgresql.DataCatalogManager4Postgresql;
import cn.edu.cug.cs.gtl.utils.postgresql.DataGroupManager4Postgresql;
import cn.edu.cug.cs.gtl.utils.postgresql.PostgresqlUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;

import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.net.URI;
import java.sql.SQLException;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.UUID;

public class AddNewItemAction extends AbstractAction {
    @Override
    public void initialize(AbstractApplication theApp) {
        this.theApp = theApp;
        ResourceBundle resourceBundle = ResourceBundle.getBundle("catalog-resource", Locale.getDefault());

        name = resourceBundle.getString("popupmenu.catalog.tree.add_new_item");
        menuItem.setText(name);
        menuItem.addActionListener(this);
        ((CatalogTree) (theApp.getMainFrame().getCatalogPanel().getTreeComponent())).getGroupNodePopupMenu().add(menuItem);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //弹出文件对话框选择文件
//        JFileChooser fileChooser = new JFileChooser(FileSystemView.getFileSystemView());  //参数为文件对话框打开的默认路径，这里设置为文档
        JFileChooser fileChooser = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
        fileChooser.setDialogTitle("选择文件作为数据项");
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);    //设置文件选择模式，可以选择文件或目录
        int returnValue = fileChooser.showOpenDialog(null);   //显示文件对话框
        // 处理用户的选择
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            try {
                File selectedFile = fileChooser.getSelectedFile();
                String localFilePath = selectedFile.getAbsolutePath();    // 获取选择的本地文件路径
                String fileAlias = selectedFile.getName(); // 获取选择的本地文件名
                String extension = fileAlias.substring(fileAlias.lastIndexOf(".")).substring(1); //截取原始文件名的后缀
                String fileName = UUID.randomUUID().toString() + extension; //构造新文件名称，uuid方式
                String hdfsPath = "hdfs://124.71.34.100:8020/data/lake/" + fileName;    // 设置上传的hdfs文件路径

                Configuration configuration = new Configuration();
                configuration.set("dfs.client.use.datanode.hostname", "true");
                FileSystem fileSystem = FileSystem.get(new URI("hdfs://124.71.34.100:8020/"), configuration, "root");

                // 检查HDFS路径是否存在
                Path hdfsDestPath = new Path(hdfsPath);
                if (fileSystem.exists(hdfsDestPath)) {
                    System.err.println("HDFS路径已经存在");
                    return;
                }
                fileSystem.copyFromLocalFile(new Path(localFilePath), hdfsDestPath); //上传本地文件到hdfs，需要本地配置host文件
                boolean uploadSuccess = fileSystem.exists(hdfsDestPath); // 上传本地文件到hdfs并检查是否成功
                if (uploadSuccess) {
                    FileKey fileKey = FileKey.newBuilder().setUrl(hdfsPath).setFileName(fileName).setFileAlias(fileAlias).build();
                    DataKey dataKey = DataKey.newBuilder().setFileKey(fileKey).build();
                    createTreeNodeAddToTree(fileName, fileAlias, extension, dataKey);   //在JTree对象中创建一个新节点
                } else JOptionPane.showMessageDialog(null, "上传失败", "错误", JOptionPane.ERROR_MESSAGE);
                fileSystem.close(); // 关闭文件系统
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        } else System.err.println("用户取消了选择");
    }

    private void createTreeNodeAddToTree(String fileName, String fileAlias, String extension, DataKey dataKey) throws SQLException {
        CatalogTree tree = (CatalogTree) theApp.getMainFrame().getCatalogPanel().getTreeComponent();
        DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        DataGroup dataGroup = (DataGroup) ((TreeNodeData) (selectNode.getUserObject())).getRefObject();
        DataItem newItem = DataItem.newBuilder().setName(fileName).setAlias(fileAlias).setFormat(extension).setKey(dataKey).build();
        new DataItemManagerImpl().insertDataItem(newItem);
        boolean ret = new DataGroupManager4Postgresql().addDataItemToGroup(dataGroup.getName(), newItem.getName());
        if (!ret)
            JOptionPane.showMessageDialog(null, "插入失败，可能dataItem表中不存在名称为" + newItem.getName() + "的对象", "错误", JOptionPane.ERROR_MESSAGE);

        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(new TreeNodeData(newItem, newItem.getAlias(), true), false);

        DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel();
        treeModel.insertNodeInto(newNode, selectNode, selectNode.getChildCount());

        TreeNode[] nodes = treeModel.getPathToRoot(newNode);
        tree.scrollPathToVisible(new TreePath(nodes));
    }
}
